package net.htjs.mobile.android.crm;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import net.htjs.mobile.android.crm.db.DatabaseHandler;
import net.htjs.mobile.android.crm.db.UserInfo;
import net.htjs.mobile.android.crm.util.L;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
	private Button login,vpnconnect;
	EditText userN;
	EditText pssW;
	
	private static String TAG="LoginActivity";
	static DatabaseHandler dbh;
	static boolean isRecordUserInfo = false;
	
	
	//VPN连接服务相关
	private BroadcastReceiver stateBroadcastReceiver;
	
	
	//屏幕事件相关
	//private GestureDetector gd;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);

		userN = (EditText) this.findViewById(R.id.username_edit);
		pssW = (EditText) this.findViewById(R.id.password_edit);
		userN.setText("zhangweitao");
		pssW.setText("z412213");
		
		
		
		/*
		 * recorduserinfo = (CheckBox) findViewById(R.id.recorduserinfo);
		 * recorduserinfo .setOnCheckedChangeListener(new
		 * CompoundButton.OnCheckedChangeListener() { public void
		 * onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //
		 * TODO Auto-generated method stub if (isChecked) { isRecordUserInfo =
		 * true; } else { isRecordUserInfo = false; } } });
		 */

		/*
		 * dbh = new DatabaseHandler(this); if (!dbh.userTableIsExist()) { try {
		 * dbh.onCreate(dbh.getWritableDatabase()); } catch (Exception e) {
		 * 
		 * } } List<UserInfo> uis = dbh.getAllUserInfos(); UserInfo userinfo =
		 * null; if (uis.size() != 0) { for (UserInfo ui : uis) {
		 * System.out.println(ui.toString()); } userinfo = uis.get(uis.size() -
		 * 1); } if (userinfo == null) { userN.setText(""); pssW.setText(""); }
		 * else { userN.setText(userinfo.getName());
		 * pssW.setText(userinfo.getPassword()); }
		 */
		
		
		
		
        
        
        
		login = (Button) this.findViewById(R.id.signin_button);
		login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				//disconnect();
				L.C.loginFlag = false;
				L.C.startLoginTime = System.currentTimeMillis();
				L.C.isLoginTimeOut=false;
				final ProgressDialog pdialog = ProgressDialog.show(
						LoginActivity.this, "", "登录中...", true);
				new Thread(new Runnable() {

					public void run() {
						
						Looper.prepare();
						// TODO Auto-generated method stub
						while (true) {
							if (L.C.loginFlag) {
								break;
							}
							long timeNow = System.currentTimeMillis();
							if (timeNow - L.C.startLoginTime > L.C.MAXTIMETOLOGIN) {
								pdialog.dismiss();
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);

								builder.setTitle("提示");
								builder.setIcon(R.drawable.logo);
								builder.setMessage("连接超时");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												L.C.isLoginTimeOut=true;//确定连接超时
												dialog.dismiss();
											}
										});

								builder.create().show();
								break;
							} else {
								try {
									Thread.sleep(1000l);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
						Looper.loop();
					}
					
				}).start();
				// v.getBackground().setAlpha(80);
				login.setClickable(false);
				new Thread(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub
						Looper.prepare();
						pdialog.setMessage("登录成功");
						HttpPost request = new HttpPost(L.loginUrl + "userId="
								+ userN.getText().toString().trim()
								+ "&password="
								+ pssW.getText().toString().trim());
						// 先封装一个 JSON 对象 /server/3g/login4Mobile.jsp
						JSONObject param = new JSONObject();
						try {
							param.put("userId", userN.getText().toString()
									.trim());
							param.put("password", pssW.getText().toString()
									.trim());
							// 绑定到请求 Entry
							StringEntity se = new StringEntity(param.toString());
							request.setEntity(se);
							// 发送请求
							DefaultHttpClient client = new DefaultHttpClient();
							HttpResponse httpResponse = client.execute(request);
							L.C.loginFlag = true;
							
							//如果超时，不做任何操作
							if(L.C.isLoginTimeOut){
								return;
							}
							// 得到应答的字符串，这也是一个 JSON 格式保存的数据
							String retSrc = EntityUtils.toString(httpResponse
									.getEntity());

							List<Cookie> cookies = client.getCookieStore()
									.getCookies();
							if (!cookies.isEmpty()) {
								for (int i = 0; i < cookies.size(); i++) {
									L.cookie = cookies.get(i);
								}
							}
							// 生成 JSON 对象
							System.out.println(retSrc);
							//JSONObject i = new JSONObject(retSrc.trim());
							if (retSrc.length()>1000) {
								pdialog.dismiss();
								L.LoginInfo.userName = userN.getText()
										.toString().trim();
								L.LoginInfo.password = pssW.getText()
										.toString().trim();
								/*
								 * if (isRecordUserInfo) { if
								 * (dbh.getUserInfo(L.LoginInfo.userName) !=
								 * null) { Util.dialog(LoginActivity.this,
								 * "用户名密码已经存在，是否覆盖保存？", "保存", "取消",
								 * LoginActivity.this, "updateUserInfo", new
								 * String[] { L.LoginInfo.userName,
								 * L.LoginInfo.password }, LoginActivity.this,
								 * "jumpPage", null, true); } else {
								 * 
								 * Util.dialog(LoginActivity.this, "是否保存用户名密码？",
								 * "保存", "取消", LoginActivity.this,
								 * "recordUserInfo", new String[] {
								 * L.LoginInfo.userName, L.LoginInfo.password },
								 * LoginActivity.this, "jumpPage", null, true);
								 * 
								 * recordUserInfo(L.LoginInfo.userName,
								 * L.LoginInfo.password); jumpPage(); } } else {
								 * dbh.deleteUserInfo(); jumpPage(); }
								 */

								// TODO Auto-generated method stub
								HttpPost request1 = new HttpPost(
										L.notificationUrl);

								JSONObject param1 = new JSONObject();
								try {
									// 绑定到请求 Entry
									StringEntity se1 = new StringEntity(param
											.toString());
									request1.setEntity(se1);
									// 发送请求
									DefaultHttpClient client1 = new DefaultHttpClient();
									client1.getCookieStore()
											.addCookie(L.cookie);
									HttpResponse httpResponse1 = client1
											.execute(request1);
									// 得到应答的字符串，这也是一个 JSON 格式保存的数据
									String retSrc1 = EntityUtils
											.toString(httpResponse1.getEntity());
									// 生成 JSON 对象
									System.out.println("______________________"
											+ retSrc1);
									JSONArray ja = new JSONArray(retSrc1.trim()
											.replaceAll("msg", "")
											.replaceAll("=", ""));
									for (int ii = 0; ii < ja.length(); ii++) {
										JSONObject jo = ja.getJSONObject(ii);
										L.notificationNum.put(
												jo.getString("mkxkid"),
												jo.getString("count"));
									}

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									//如果超时，不做任何操作
									if(L.C.isLoginTimeOut){
										return;
									}
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									//如果超时，不做任何操作
									if(L.C.isLoginTimeOut){
										return;
									}
								} catch (ClientProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									//如果超时，不做任何操作
									if(L.C.isLoginTimeOut){
										return;
									}
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									//如果超时，不做任何操作
									if(L.C.isLoginTimeOut){
										return;
									}
								}

								jumpPage();
							} else {
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage("密码错误");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});

								builder.create().show();
							}
							L.C.loginFlag = true;
							
							//如果超时，不做任何操作
							if(L.C.isLoginTimeOut){
								return;
							}
							// JSONObject result = new JSONObject(retSrc);
							// String token = (String) result.get("token");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						pdialog.dismiss();
						login.setClickable(true);
						Looper.loop();
					}
					
				}).start();
			}
		});
		
		 
	}
	
	 

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	public boolean jumpPage() {
		Intent mainIntent = new Intent(getApplication(), Main.class);
		startActivity(mainIntent);
		return true;
	}

	public boolean recordUserInfo(String userName, String password) {

		dbh.addUserInfo(new UserInfo().setName(userName).setPassword(password));

		return true;
	}

	public boolean updateUserInfo(String userName, String password) {

		dbh.updateUserInfo(new UserInfo().setName(userName).setPassword(
				password));

		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				finish();
				return true;
			}

		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void finish(){
		
		super.finish();
	}
}